package com.eds.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eds.exception.BusException;
import com.eds.feign.CourseFeign;
import com.eds.feign.UserService;
import com.eds.log.LogUtil;
import com.eds.mapper.ConversationMapper;
import com.eds.mapper.MessageMapper;
import com.eds.pojo.CodeEnum;
import com.eds.pojo.RecommendationDTO;
import com.eds.redis.RedisRecommendationCacheService;
import com.eds.service.AiService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pojo.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.*;
import java.util.stream.Collectors;

/**
 * AI服务实现类
 * 实现AI聊天功能的所有业务逻辑
 */
@Service
public class AiServiceImpl implements AiService {
    private static final Logger logger = LogUtil.getLogger(AiServiceImpl.class);

    //会话Mapper
    @Autowired
    private ConversationMapper conversationMapper;


    //消息Mapper
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private RedisRecommendationCacheService redisRecommendationCache;
    //用户服务Feign客户端
    @Autowired
    private UserService userService;
    @Autowired
    private CourseFeign courseFeign;

    //WebClient客户端，用于调用AI模型API
    @Autowired
    private WebClient webClient;


    /* *
     * @Title: processMessage
     * @Author: vvSmile
     * @Date: 2025-04-09 18:03:12
     * @param message 用户发送的消息内容
     * @param conversationId 会话ID，如果为null则创建新会话
     * @param token  用户认证令牌
     * @return Map<Object>
     * @Description: TODO 处理用户发送的消息并获取AI回复
     */
    @Override
    @Transactional
    public Map<String, Object> processMessage(String message, Long conversationId, String token) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 获取用户信息
            Long userIdFromToken = userService.getUserIdFromToken(token);
            if (userIdFromToken == null) {
                throw new BusException(CodeEnum.TOKEN_IS_NULL.getCode(), CodeEnum.TOKEN_IS_NULL.getMessage(), new Exception("Token is null"));
            }

            // 如果没有传入conversationId，则创建新会话
            if (conversationId == null) {
                AiConversation newConversation = new AiConversation();
                newConversation.setUserId(userIdFromToken);
                newConversation.setTitle("新对话"); // 默认标题
                newConversation.setCreatedAt(new Date());
                newConversation.setUpdatedAt(new Date());
                newConversation.setIsDeleted(0); // 0表示未删除
                int insert = conversationMapper.insert(newConversation);
                if (insert < 0) {
                    throw new BusException(CodeEnum.CREATE_CONVERSATION_ERROR.getCode(), CodeEnum.CREATE_CONVERSATION_ERROR.getMessage(), new Exception("Failed to create conversation"));
                }
                LogUtil.info(AiServiceImpl.class, "新增会话" + newConversation);
                conversationId = newConversation.getConversationId();
            }

            // 保存用户消息
            AiMessage userMessage = new AiMessage();
            userMessage.setConversationId(conversationId);
            userMessage.setContent(message);
            userMessage.setRole("user"); // 用户发送的消息
            userMessage.setCreatedAt(new Date());
            userMessage.setUpdatedAt(new Date());
            userMessage.setStatus(0); // 0表示正常状态
            int insert = messageMapper.insert(userMessage);
            LogUtil.info(AiServiceImpl.class, "新增用户消息记录" + userMessage);
            if (insert < 0) {
                throw new BusException(CodeEnum.CREATE_MESSAGE_ERROR.getCode(), CodeEnum.CREATE_MESSAGE_ERROR.getMessage(), new Exception("Failed to save user message"));
            }

           /* // 构建请求AI模型的消息历史
            List<Map<String, String>> messageHistory = getMessageHistoryForModel(userMessage.getConversationId());

            // 调用AI模型获取回复
            String aiReply = callAiModel(messageHistory);*/
            String aiReply;
            // 检查用户消息是否包含"推荐"关键词
            if (message.contains("推荐")) {
                // 从Redis获取推荐数据
                List<RecommendationDTO> recommendations = redisRecommendationCache.getUserRecommendations(userIdFromToken);
                // 处理缓存未命中情况
                if (recommendations == null || recommendations.isEmpty()) {
                    aiReply = "暂时没有找到适合您的推荐内容";
                    LogUtil.warn(AiServiceImpl.class, "Redis未找到推荐数据, userId: " + userIdFromToken);
                } else {
                    // 将推荐列表转换为自然语言回复
                    aiReply = formatRecommendations(recommendations);
                    LogUtil.info(AiServiceImpl.class, "从Redis获取推荐数据, 数量: " + recommendations.size());
                }
            } else {
                // 正常AI处理流程
                List<Map<String, String>> messageHistory = getMessageHistoryForModel(userMessage.getConversationId());
                aiReply = callAiModel(messageHistory);
            }

            // 保存AI回复
            AiMessage aiMessage = new AiMessage();
            aiMessage.setConversationId(conversationId);
            aiMessage.setContent(aiReply);
            aiMessage.setRole("assistant"); // AI回复的消息
            aiMessage.setCreatedAt(new Date());
            aiMessage.setUpdatedAt(new Date());
            aiMessage.setStatus(0); // 0表示正常状态
            int insert1 = messageMapper.insert(aiMessage);
            LogUtil.info(AiServiceImpl.class, "新增AI消息记录" + aiMessage);
            if (insert1 < 0) {
                throw new BusException(CodeEnum.AI_TALK_ERROR.getCode(), CodeEnum.AI_TALK_ERROR.getMessage(), new Exception("Failed to save AI reply"));
            }

            // 更新会话的最后一条消息和更新时间
            AiConversation conversation = new AiConversation();
            conversation.setConversationId(conversationId);
            conversation.setLastMessage(message.length() > 50 ? message.substring(0, 50) + "..." : message);
            conversation.setUpdatedAt(new Date());
            int update = conversationMapper.updateById(conversation);
            LogUtil.info(AiServiceImpl.class, "更新会话的最后一条消息和更新时间" + conversation);
            if (update < 0) {
                throw new BusException(CodeEnum.UPDATE_LAST_MESSAGE_DATE_ERROR.getCode(), CodeEnum.UPDATE_LAST_MESSAGE_DATE_ERROR.getMessage(), new Exception("Failed to update last message"));
            }

            // 构建响应
            response.put("code", 200);
            response.put("message", "处理成功");
            response.put("data", aiReply);
            response.put("conversationId", conversationId);
            return response;
        } catch (Exception e) {
            // 记录完整的异常信息
            LogUtil.error(AiServiceImpl.class, "处理消息时发生错误", e);

            // 构建响应
            response.put("code", 500);
            response.put("message", "处理消息时发生错误: " + e.getMessage());
            return response;
        }
    }
    // 推荐列表转自然语言格式
    private String formatRecommendations(List<RecommendationDTO> recommendations) {
        StringBuilder recommendationsText = new StringBuilder("为您推荐以下内容：\n\n");

        // 限制最多5条推荐
        int limit = Math.min(recommendations.size(), 5);
        for (int i = 0; i < limit; i++) {
            RecommendationDTO item = recommendations.get(i);
            recommendationsText.append(i + 1).append(". **").append(item.getTitle()).append("**");

            // 添加描述（如果有）
            if (item.getDescription() != null && !item.getDescription().isEmpty()) {
                // 截断过长的描述
                String desc = item.getDescription().length() > 100 ?
                        item.getDescription().substring(0, 100) + "..." :
                        item.getDescription();
                recommendationsText.append("\n   - ").append(desc);
            }

            // 添加类型信息
            String typeName = getTypeName(item.getType());
            recommendationsText.append("\n   - 类型: ").append(typeName);

            // 添加链接（如果有）
            if (item.getTargetUrl() != null && !item.getTargetUrl().isEmpty()) {
                recommendationsText.append("\n   - 链接: ").append(item.getTargetUrl());
            }
            recommendationsText.append("\n\n");
        }

        // 添加查看更多提示
        if (recommendations.size() > limit) {
            recommendationsText.append("还有").append(recommendations.size() - limit)
                    .append("条推荐内容，请查看完整推荐列表");
        }

        return recommendationsText.toString();
    }

    // 推荐类型转换方法
    private String getTypeName(Integer type) {
        if (type == null) return "未知类型";

        switch (type) {
            case 1: return "学术";
            case 2: return "技术与工程";
            case 3: return "艺术与设计";
            case 4: return "职业技能";
            case 5: return "健康与医学";
            case 6: return "语言与文化 ";
            case 7: return "科技与未来趋势";
            case 8: return "体育与健身";
            default: return "其他资源";
        }
    }

    /* *
     * @Title: getUserConversations
     * @Author: vvSmile
     * @Date: 2025-04-09 18:02:57
     * @param token  用户认证令牌
     * @return List<AiConversation> 对话列表
     * @Description: TODO 获取用户的所有对话列表
     */
    @Override
    public List<AiConversation> getUserConversations(String token) {
        try {
            // 获取用户信息
            Long userIdFromToken = userService.getUserIdFromToken(token);
            if (userIdFromToken == null) {
                return Collections.emptyList();
            }
            // 查询用户的所有未删除会话
            return conversationMapper.findByUserIdAndNotDeleted(userIdFromToken);
        } catch (Exception e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
    }


    /* *
     * @Title: getConversationHistory
     * @Author: vvSmile
     * @Date: 2025-04-09 18:03:38
     * @param conversationId 会话ID
     * @param token  用户认证令牌
     * @return List<AiMessage> 消息列表
     * @Description: TODO 获取特定对话的消息历史
     */
    @Override
    public List<AiMessage> getConversationHistory(Long conversationId, String token) {
        try {
            // 获取用户信息
            Long userIdFromToken = userService.getUserIdFromToken(token);
            if (userIdFromToken == null) {
                return Collections.emptyList();
            }

            // 验证会话是否属于该用户
            QueryWrapper<AiConversation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("conversation_id", conversationId).eq("user_id", userIdFromToken);
            AiConversation conversation = conversationMapper.selectOne(queryWrapper);

            if (conversation == null) {
                return Collections.emptyList();
            }

            // 查询会话的所有消息
            return messageMapper.findByConversationIdAndNormalStatus(conversationId);
        } catch (Exception e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
    }


    /* *
     * @Title: createConversation
     * @Author: vvSmile
     * @Date: 2025-04-09 18:03:51
     * @param title 对话标题
     * @param token  用户认证令牌
     * @return Long 新创建的对话ID
     * @Description: TODO 创建新的对话
     */
    @Override
    @Transactional
    public Long createConversation(String title, String token) {
        try {
            // 获取用户信息
            Long userIdFromToken = userService.getUserIdFromToken(token);
            if (userIdFromToken == null) {
                return null;
            }
            // 创建新会话
            AiConversation conversation = new AiConversation();
            conversation.setUserId(userIdFromToken);
            conversation.setTitle(title);
            conversation.setCreatedAt(new Date());
            conversation.setUpdatedAt(new Date());
            conversation.setIsDeleted(0); // 0表示未删除
            conversationMapper.insert(conversation);
            return conversation.getConversationId();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /* *
     * @Title: deleteConversation
     * @Author: vvSmile
     * @Date: 2025-04-09 18:04:18
     * @param conversationId 要删除的对话ID
     * @param token  用户认证令牌
     * @return boolean 操作是否成功
     * @Description: TODO 删除对话
     */
    @Override
    @Transactional
    public boolean deleteConversation(Long conversationId, String token) {
        try {
            // 获取用户信息
            Long userIdFromToken = userService.getUserIdFromToken(token);
            if (userIdFromToken == null) {
                throw new BusException(CodeEnum.TOKEN_IS_NULL.getCode(), CodeEnum.TOKEN_IS_NULL.getMessage());
            }
            // 验证会话是否属于该用户
            QueryWrapper<AiConversation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("conversation_id", conversationId)
                    .eq("user_id", userIdFromToken);
            AiConversation conversation = conversationMapper.selectOne(queryWrapper);
            if (conversation == null) {
                throw new BusException(CodeEnum.CONVERSATION_IS_NOT_BELONG_USER.getCode(), CodeEnum.CONVERSATION_IS_NOT_BELONG_USER.getMessage());
            }

            // 逻辑删除会话（标记为已删除）
            UpdateWrapper<AiConversation> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("conversation_id", conversationId)
                    .set("is_deleted", 1); // 1表示已删除
            LogUtil.info(AiServiceImpl.class, "逻辑删除会话" + conversationId);
            int rows = conversationMapper.update(null, updateWrapper);
            return rows > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /* *
     * @Title: getMessageHistoryForModel
     * @Author: vvSmile
     * @Date: 2025-04-09 18:04:35
     * @param conversationId  会话ID
     * @return List<Map<String>> 格式化后的消息历史列表
     * @Description: TODO 获取特定会话的消息历史，格式化为调用AI模型的格式
     */
    private List<Map<String, String>> getMessageHistoryForModel(Long conversationId) {
        //根据conversationId查询所有的消息
        List<AiMessage> messages = messageMapper.findByConversationIdAndNormalStatus(conversationId);
        List<Map<String, String>> formattedMessages = new ArrayList<>();
        // 转换消息格式
        for (AiMessage message : messages) {
            Map<String, String> formattedMessage = new HashMap<>();
            formattedMessage.put("role", message.getRole());
            formattedMessage.put("content", message.getContent());
            formattedMessages.add(formattedMessage);
        }
        return formattedMessages;
    }


    /* *
     * @Title: callAiModel
     * @Author: vvSmile
     * @Date: 2025-04-09 18:04:54
     * @param messageHistory  消息历史
     * @return String AI模型的回复
     * @Description: TODO 调用AI模型API获取回复
     */
    private String callAiModel(List<Map<String, String>> messageHistory) {
        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("messages", messageHistory);
            requestBody.put("temperature", 0.7);
            requestBody.put("max_tokens", 2000);

            // 发送请求并获取响应
            Map response = webClient.post()
                    .uri("/v1/chat/completions")//设置请求的 URI 路径
                    .bodyValue(requestBody)//设置请求体内容
                    .retrieve()//开始执行请求
                    .bodyToMono(Map.class)//表示将响应体解析为 Map 类型
                    .block();//阻塞等待响应结果（将异步转为同步）

            // 解析响应
            if (response != null && response.containsKey("choices")) {
                List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
                if (!choices.isEmpty()) {
                    Map<String, Object> choice = choices.get(0);
                    Map<String, String> message = (Map<String, String>) choice.get("message");
                    return message.get("content");
                }
            }

            return "抱歉，我无法生成回复。";
        } catch (Exception e) {
            e.printStackTrace();
            return "发生错误: " + e.getMessage();
        }
    }

    /* *
     * @Title: getRecommendationsForUser
     * @Author: vvSmile
     * @Date: 2025-04-10 10:48:39
     * @param userId
     * @return List<RecommendationDTO>
     * @Description: TODO 用户推荐
     */
    @Override
    public List<RecommendationDTO> getRecommendationsForUser(Long userId) {
        logger.info("开始为用户[{}]获取AI个性化推荐", userId);
        long startTime = System.currentTimeMillis();

        try {
            // 1. 获取用户信息
            User user = userService.getUserByUserId(userId);
            if (user == null) {
                logger.error("用户[{}]不存在", userId);
                return getHotRecommendations();
            }

            // 2. 构建并发送AI请求
            Map<String, Object> requestBody = buildAIRequest(user);
            Map response = sendAIRequest(requestBody);

            // 3. 解析响应
            List<RecommendationDTO> recommendations = parseAIResponse(response);

            long endTime = System.currentTimeMillis();
            logger.info("用户[{}]的推荐列表获取成功，共[{}]条，耗时[{}]ms",
                    userId, recommendations.size(), (endTime - startTime));

            return recommendations;
        } catch (Exception e) {
            logger.error("用户[{}]的推荐列表获取失败，返回热门推荐", userId, e);
            return getHotRecommendations();
        }
    }

    /* *
     * @Title: getHotRecommendations
     * @Author: vvSmile
     * @Date: 2025-04-10 10:49:00
     * @return List<RecommendationDTO>
     * @Description: TODO 热门推荐
     */
    @Override
    public List<RecommendationDTO> getHotRecommendations() {
        logger.info("开始获取热门推荐列表");
        long startTime = System.currentTimeMillis();

        try {
            // 1. 构建并发送AI请求
            Map<String, Object> requestBody = buildHotRecommendationRequest();
            Map response = sendAIRequest(requestBody);

            // 2. 解析响应
            List<RecommendationDTO> recommendations = parseAIResponse(response);

            long endTime = System.currentTimeMillis();
            logger.info("获取热门推荐成功，耗时[{}]ms，共[{}]条推荐",
                    (endTime - startTime), recommendations.size());

            return recommendations;
        } catch (Exception e) {
            logger.error("获取热门推荐异常", e);
            return getFallbackRecommendations();
        }
    }


    /* *
     * @Title: hotCacheChangeRecommendationDtoToCourse
     * @Author: vvSmile
     * @Date: 2025-04-10 10:49:12
     * @return List<Course>
     * @Description: TODO 转换热门推荐列表为课程列表
     */
    @Override
    public List<Course> hotCacheChangeRecommendationDtoToCourse() {
        ArrayList<Course> list = new ArrayList<>();
        for (RecommendationDTO hotRecommendation : redisRecommendationCache.getHotRecommendations()) {
            Long id = hotRecommendation.getId();
            Course course = courseFeign.selectCourseByCourseIdReturnCourse(id);
            list.add(course);
        }
        return list;
    }

    /* *
     * @Title: userCacheChangeRecommendationDtoToCourse
     * @Author: vvSmile
     * @Date: 2025-04-10 10:49:26
     * @return List<Course>
     * @Description: TODO 转换用户推荐列表为课程列表
     */
    @Override
    public List<Course> userCacheChangeRecommendationDtoToCourse(String token) {
        Long userId = userService.getUserIdFromToken(token);
        List<RecommendationDTO> userRecommendations = redisRecommendationCache.getUserRecommendations(userId);
        if (userRecommendations != null) {
            ArrayList<Course> list = new ArrayList<>();
            for (RecommendationDTO userRecommendation : userRecommendations) {
                Long id = userRecommendation.getId();
                Course course = courseFeign.selectCourseByCourseIdReturnCourse(id);
                list.add(course);
            }
            return list;
        }
        return null;
    }

    /* *
     * @Title: getHappyRecommendations
     * @Author: vvSmile
     * @Date: 2025-04-10 14:06:06
     * @return List<RecommendationDTO>
     * @Description: TODO 获取开心一刻的推荐列表
     */
    @Override
    public List getHappyRecommendations() {
        try {
            // 1. 构建并发送AI请求
            Map<String, Object> requestBody = buildHappyRecommendationRequest();
            Map response = sendAIRequest(requestBody);
            // 2. 解析响应
            List recommendations = parseContentToList(response);
            return recommendations;
        } catch (Exception e) {
            logger.error("获取开心一刻推荐列表异常", e);
            return null;
        }
    }

    @Override
    public String happyCacheChangeRecommendationDtoToCourse() {

        Object happyRecommendations = redisRecommendationCache.getHappyRecommendations();
        // 添加类型日志以便调试
        if (happyRecommendations != null) {
            logger.info("获取的happy数据类型: {}", happyRecommendations.getClass().getName());
        } else {
            logger.warn("Redis中没有找到开心一刻数据");
        }

        // 获取随机内容
        String happy = getRandomContent((List<String>) happyRecommendations);
        if (happy == null) {
            String defaultHappyContent = getDefaultHappyContent();
            return defaultHappyContent;
        }

        logger.info("成功获取随机开心一刻内容: {}", happy);
        return happy;
    }

    // 构建开心一刻的AI请求
    private Map<String, Object> buildHappyRecommendationRequest() {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("messages", buildHappyRecommendationMessages());
        requestBody.put("temperature", 1.0);
        requestBody.put("max_tokens", 2000);
        return requestBody;
    }

    // 构建开心一刻的AI消息
    private Object buildHappyRecommendationMessages() {
        List<Map<String, String>> messages = new ArrayList<>();

        // 系统消息
        Map<String, String> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", "你是一个幽默的内容创作者，需要生成简短有趣正能量学习的「开心一刻」内容，禁止重复内容。\n" +
                "要求：\n" +
                "1. 返回格式必须是JSON数组，每个项目包含以下字段：\n" +
                "2. 返回的JSON不要包含任何markdown标记\n" +
                "3. 生成100条不同的内容\n" +
                "4. 内容需要100条每日一言语句\n" +
                "5. 每条内容必须控制在20-30字以内");
        messages.add(systemMessage);
        return messages;
    }

    // 构建AI请求
    private Map<String, Object> buildAIRequest(User user) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("messages", buildUserRecommendationMessages(user));
        requestBody.put("temperature", 0.7);
        requestBody.put("max_tokens", 2000);
        return requestBody;
    }

    // 构建热门推荐请求
    private Map<String, Object> buildHotRecommendationRequest() {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("messages", buildHotRecommendationMessages());
        requestBody.put("temperature", 0.7);
        requestBody.put("max_tokens", 2000);
        return requestBody;
    }

    // 发送AI请求
    private Map sendAIRequest(Map<String, Object> requestBody) {
        return webClient.post()
                .uri("/v1/chat/completions")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .block();
    }

    private List<Map<String, String>> buildUserRecommendationMessages(User user) {
        List<Map<String, String>> messages = new ArrayList<>();

        // 系统消息
        Map<String, String> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", "你是一个课程推荐系统，根据用户信息和课程数据生成8个热门课程推荐。\n" +
                "要求：\n" +
                "1. 返回格式必须是JSON数组，每个推荐项包含以下字段：\n" +
                "   - id: 课程id\n" +
                "   - course: 课程名称\n" +
                "   - description: 课程描述\n" +
                "   - type: 课程类型（1-8）\n" +
                "   - score: 推荐分数（1-5）\n" +
                "2. 返回的JSON不要包含任何markdown标记\n" +
                "3. 推荐内容要突出课程特色和教学优势\n" +
                "4. 推荐标题要简洁明了，描述要详细具体\n" +
                "5. 根据用户偏好和课程内容合理设置类型和分数");
        messages.add(systemMessage);

        // 用户消息
        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");

        // 构建用户数据JSON
        Map<String, Object> userData = new HashMap<>();
        userData.put("userId", user.getUserId());
        userData.put("userName", user.getUserName());
        userData.put("gender", user.getGender());
        userData.put("education", user.getEducation());
        userData.put("school", user.getSchool());
        userData.put("role", user.getRole());

        // 添加用户偏好
        if (user.getUserPreferences() != null) {
            UserPreference preferences = user.getUserPreferences();
            Map<String, Integer> teachingStylePreferences = new HashMap<>();
            teachingStylePreferences.put("traditional", preferences.getTraditionalStyle());
            teachingStylePreferences.put("interactive", preferences.getInteractiveDiscussionStyle());
            teachingStylePreferences.put("caseStudy", preferences.getCaseStudyStyle());
            teachingStylePreferences.put("gamified", preferences.getGamifiedLearningStyle());
            teachingStylePreferences.put("emotional", preferences.getEmotionalMotivationStyle());
            teachingStylePreferences.put("humorous", preferences.getHumorousStyle());
            teachingStylePreferences.put("guided", preferences.getGuidedLearningStyle());
            teachingStylePreferences.put("personalized", preferences.getPersonalizedLearningStyle());
            teachingStylePreferences.put("flipped", preferences.getFlippedClassroomStyle());
            userData.put("teachingStylePreferences", teachingStylePreferences);
        }

        // 添加课程数据
        List<Map<String, Object>> coursesData = new ArrayList<>();
        for (User teacher : userService.getAllTeachersCourses()) {
            Map<String, Object> teacherData = new HashMap<>();
            teacherData.put("teacherName", teacher.getUserName());
            teacherData.put("education", teacher.getEducation());
            teacherData.put("school", teacher.getSchool());
            teacherData.put("teachingAge", teacher.getTeacher().getTeachingAge());
            teacherData.put("teachingStyle", teacher.getTeacher().getTeachingStyle());
            teacherData.put("rating", teacher.getTeacher().getRating());

            List<Map<String, Object>> teacherCourses = teacher.getCourses().stream()
                    .map(course -> {
                        Map<String, Object> courseData = new HashMap<>();
                        courseData.put("id", course.getCourseId());
                        courseData.put("title", course.getTitle());
                        courseData.put("details", course.getDetails());
                        courseData.put("categoryId", course.getCategoryId());
                        courseData.put("price", course.getPrice());
                        courseData.put("status", course.getStatus());
                        courseData.put("recommendWeight", course.getRecommendWeight());
                        courseData.put("studyPeople", course.getStudyPeople());
                        courseData.put("titleImg", course.getTitleImg());
                        return courseData;
                    })
                    .collect(Collectors.toList());
            teacherData.put("courses", teacherCourses);

            coursesData.add(teacherData);
        }
        userData.put("availableCourses", coursesData);

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            userMessage.put("content", objectMapper.writeValueAsString(userData));
        } catch (JsonProcessingException e) {
            logger.error("构建用户数据JSON失败", e);
            userMessage.put("content", "无法构建用户数据");
        }

        messages.add(userMessage);
        return messages;
    }

    // 构建热门推荐消息
    private List<Map<String, String>> buildHotRecommendationMessages() {
        List<Map<String, String>> messages = new ArrayList<>();

        // 系统消息
        Map<String, String> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", "你是一个课程推荐系统，根据课程数据生成8个热门课程推荐。\n" +
                "要求：\n" +
                "1. 返回格式必须是JSON数组，每个推荐项包含以下字段：\n" +
                "   - id: 课程id\n" +
                "   - course: 课程名称\n" +
                "   - description: 课程描述\n" +
                "   - type: 课程类型（1-8）\n" +
                "   - score: 推荐分数（1-5）\n" +
                "2. 返回的JSON不要包含任何markdown标记\n" +
                "3. 推荐内容要突出课程特色和教学优势\n" +
                "4. 推荐标题要简洁明了，描述要详细具体\n" +
                "5. 根据课程内容合理设置类型和分数");
        messages.add(systemMessage);

        // 用户消息
        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");

        // 构建课程数据JSON
        List<Map<String, Object>> coursesData = new ArrayList<>();
        for (User teacher : userService.getAllTeachersCourses()) {
            Map<String, Object> teacherData = new HashMap<>();
            teacherData.put("teacherName", teacher.getUserName());
            teacherData.put("education", teacher.getEducation());
            teacherData.put("school", teacher.getSchool());
            teacherData.put("teachingAge", teacher.getTeacher().getTeachingAge());
            teacherData.put("teachingStyle", teacher.getTeacher().getTeachingStyle());
            teacherData.put("rating", teacher.getTeacher().getRating());

            List<Map<String, Object>> teacherCourses = teacher.getCourses().stream()
                    .map(course -> {
                        Map<String, Object> courseData = new HashMap<>();
                        courseData.put("id", course.getCourseId());
                        courseData.put("课程名", course.getTitle());
                        courseData.put("details", course.getDetails());
                        courseData.put("categoryId", course.getCategoryId());
                        courseData.put("price", course.getPrice());
                        courseData.put("status", course.getStatus());
                        courseData.put("recommendWeight", course.getRecommendWeight());
                        courseData.put("createTime", course.getCreateTime());
                        courseData.put("studyPeople", course.getStudyPeople());
                        courseData.put("titleImg", course.getTitleImg());
                        return courseData;
                    })
                    .collect(Collectors.toList());
            teacherData.put("courses", teacherCourses);

            coursesData.add(teacherData);
        }

        try {
            ObjectMapper mapper = new ObjectMapper();
            userMessage.put("content", mapper.writeValueAsString(coursesData));
        } catch (JsonProcessingException e) {
            logger.error("构建课程数据JSON失败", e);
            userMessage.put("content", "无法构建课程数据");
        }

        messages.add(userMessage);
        return messages;
    }

    // 解析AI响应
    private List<RecommendationDTO> parseAIResponse(Map<String, Object> response) {
        if (response == null || !response.containsKey("choices")) {
            logger.error("AI响应格式错误");
            return new ArrayList<>();
        }

        List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
        if (choices.isEmpty()) {
            logger.error("AI响应为空");
            return new ArrayList<>();
        }

        Map<String, Object> choice = choices.get(0);
        Map<String, String> message = (Map<String, String>) choice.get("message");
        String content = message.get("content");

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 清理JSON字符串（移除可能的markdown标记）
            content = content.replace("```json", "").replace("```", "").trim();

            // 解析JSON数组
            List<Map<String, Object>> recommendations = objectMapper.readValue(content,
                    new TypeReference<List<Map<String, Object>>>() {
                    });

            // 转换为RecommendationDTO列表
            return recommendations.stream()
                    .map(this::convertToRecommendationDTO)
                    .collect(Collectors.toList());
        } catch (JsonProcessingException e) {
            logger.error("解析AI响应失败", e);
            return getFallbackRecommendations();
        }
    }
    // 将Map转换为RecommendationDTO
    private RecommendationDTO convertToRecommendationDTO(Map<String, Object> map) {
        RecommendationDTO dto = new RecommendationDTO();

        // 设置基本属性
        dto.setId((Long) map.get("id"));
        dto.setTitle((String) map.get("course"));
        dto.setDescription((String) map.get("description"));

        // 处理类型
        Object typeObj = map.get("type");
        if (typeObj instanceof Number) {
            dto.setType(((Number) typeObj).intValue());
        } else if (typeObj instanceof String) {
            dto.setType(Integer.parseInt((String) typeObj));
        }

        // 处理分数
        Object scoreObj = map.get("score");
        if (scoreObj instanceof Number) {
            dto.setScore(((Number) scoreObj).doubleValue());
        } else if (scoreObj instanceof String) {
            dto.setScore(Double.parseDouble((String) scoreObj));
        }

        return dto;
    }

    // 获取备用推荐
    private List<RecommendationDTO> getFallbackRecommendations() {
        logger.info("使用备用推荐数据");
        List<RecommendationDTO> fallback = new ArrayList<>();

        // 获取热门课程作为备用推荐，获取前5个热门课程
        List<Course> hotCourses = courseFeign.getHotCourses(5);
        for (Course course : hotCourses) {
            RecommendationDTO rec = new RecommendationDTO();
            rec.setId(course.getCourseId());
            rec.setTitle(course.getTitle());
            rec.setDescription(course.getDetails());
            rec.setImageUrl(course.getTitleImg());
            rec.setType(1);
            rec.setScore(course.getRecommendWeight() != null ? course.getRecommendWeight().doubleValue() : 0.0);
            rec.setCreateTime(course.getCreateTime());
            fallback.add(rec);
        }

        return fallback;
    }


    /**
     * 从AI响应中提取content并存入List
     *
     * @param response AI响应对象
     * @return 解析happy的Content列表
     */
    public List<String> parseContentToList(Map<String, Object> response) {
        List<String> resultList = new ArrayList<>();

        try {
            // 提取content
            String content = extractContentFromAIResponse(response);
            if (content.isEmpty()) {
                logger.error("提取的content为空");
                return resultList;
            }

            // 解析JSON数组
            ObjectMapper mapper = new ObjectMapper();
            JsonNode contentArray = mapper.readTree(content);

            // 判断是否为数组
            if (contentArray.isArray()) {
                // 遍历数组元素
                for (int i = 0; i < contentArray.size() && i < 100; i++) {
                    JsonNode item = contentArray.get(i);

                    // 尝试提取content字段
                    if (item.has("content")) {
                        resultList.add(item.get("content").asText());
                    } else if (item.isObject()) {
                        // 处理嵌套格式，如["type", {"content": "xxx"}]格式
                        for (JsonNode field : item) {
                            if (field.isObject() && field.has("content")) {
                                resultList.add(field.get("content").asText());
                                break;
                            }
                        }
                    }
                }
                logger.info("成功将content内容存入List，共{}个元素", resultList.size());
            } else if (contentArray.isObject() && contentArray.has("content")) {
                // 如果是单个对象且有content字段
                resultList.add(contentArray.get("content").asText());
                logger.info("content是单个对象，已将其content字段添加到List");
            }

            return resultList;
        } catch (Exception e) {
            logger.error("解析content并存入List失败", e);
            return resultList;
        }
    }

    /**
     * 从AI响应中提取content内容
     *
     * @param response AI响应对象
     * @return 提取的content内容
     */
    private String extractContentFromAIResponse(Map<String, Object> response) {
        if (response == null || !response.containsKey("choices")) {
            logger.error("AI响应格式错误");
            return "";
        }

        try {
            List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
            if (choices.isEmpty()) {
                logger.error("AI响应choices为空");
                return "";
            }

            Map<String, Object> choice = choices.get(0);
            Map<String, Object> message = (Map<String, Object>) choice.get("message");
            String content = (String) message.get("content");

            // 去除markdown标记
            content = content.replace("```json", "").replace("```", "").trim();

            return content;
        } catch (Exception e) {
            logger.error("提取AI响应content失败", e);
            return "";
        }
    }

    /**
     * 从List中随机获取一条内容
     *
     * @param contentList 内容列表
     * @return 随机选择的内容
     */
    public String getRandomContent(List<String> contentList) {
        if (contentList == null || contentList.isEmpty()) {
            logger.warn("内容列表为空，无法获取随机内容");
            return null;
        }

        Random random = new Random();
        int randomIndex = random.nextInt(contentList.size());
        String randomContent = contentList.get(randomIndex);

        logger.info("成功获取随机内容: {}", randomContent);
        return randomContent;
    }




    /**
     * 获取默认的开心一刻内容
     */
    private String getDefaultHappyContent() {
        // 默认内容列表
        List<String> defaultContents = Arrays.asList(
                "生活不止眼前的苟且，还有诗和远方的田野。",
                "今天不开心没关系，明天也不会好。",
                "别低头，皇冠会掉；别流泪，眼妆会花。",
                "梦想还是要有的，万一见鬼了呢？",
                "生活就像心电图，一帆风顺就说明你挂了。"
        );

        // 随机返回一条
        return defaultContents.get(new Random().nextInt(defaultContents.size()));
    }
}